/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import prompt from '@system.prompt'
import router from '@system.router'
import http from '@ohos.net.http'
import util from '@ohos.util'

export default {
    data: {
        name: '',
        password: '',
        email: '',
        ve: '',
        token: '',
        session:'',
        success:{},
        pic:'',
        base:''
    },
    onInit() {
    },
    onDestroy() {
    },
    getName(e) {
        this.name = e.value;
        console.info("napi_name=" + this.name);
        prompt.showToast({
            message: this.$t('Strings.userNamePrompt')
        })
    },
    getPassword(e) {
        this.password = e.value;
        console.info("napi_date=" + this.password);
        prompt.showToast({
            message: this.$t('Strings.passwordPrompt')
        })
    },
    getEmail(e) {
        this.email = e.value;
        console.info("gender =" + this.email)
    },
    getVerifycode(e) {
        this.ve = e.value;
        console.info("napi_verifiedcode=" + this.ve)
    },
    onVerify() {
        let url = this.pic;
        this.$refs.canvas.clear();
        const el =this.$refs.canvas;
        var ctx =el.getContext('2d');
        ctx.clearRect(0, 0, 300, 200);
        var img = new Image();
        img.src = url;
        console.log('napi_Image load success1',img.src);
        img.onload = function() {
            console.log('napi_Image load success2');
            ctx.drawImage(img, 0, 0, 300, 200);
        };
        img.onerror = function() {
            console.log('napi_Image load fail');
        };
    },
    onLogin() {
        if (this.name.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.name_null')
            })
            return;
        }
        if (this.password.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.date_null')
            })
            return;
        }
        if (this.email.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.email_null')
            })
            return;
        }
        if (this.ve.length == 0) {
            prompt.showToast({
                message: this.$t('Strings.gender_null')
            })
            return;
        }
        let url = this.$app.$def.data.usermgmtIP + '/v1/users?verifyCode=' + this.ve;
        let httpRequest = http.createHttp();
        httpRequest.on('napi_headersReceive', (data) => {
            console.info('napi_header: ' + data.header);
        });
        let session_value = 'AUTHSERVERSESSIONID=' + this.session + ';';
        let cookie_value = session_value + 'XSRF-TOKEN=' + this.token + ';';
        httpRequest.request(
            url,
            {
                method: 'POST', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'application/json',
                    'Cookie': cookie_value,
                    'Connection': 'keep-alive',
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept': '*/*',
                    'X-XSRF-TOKEN': this.token
                },
                extraData:
                {
                    //                    "username": "TestU2haey2eer1",
                    //                    "mailAddress": "testqqaaay2w@edgegallery.org",
                    //                    "telephone": "138120456001",
                    //                    "password": "123.qwe"
                    "username": this.name,
                    "mailAddress": this.mail,
                    "password": this.password
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('napi_Result:' + data.result);
                console.info('napi_cookies:' + data.cookies);
                this.success = data.responseCode;
            } else {
                console.info('napi_error:' + err);
                httpRequest.destroy();
            }
            this.success = data.responseCode;
            if(this.success == 201) {
                router.push({
                    uri: 'pages/login/login'
                })
            } else {
                var err = JSON.parse(data.result);
                console.error("myapp register err result:" + err.code);
                if (err.code == 70011) {
                    prompt.showToast({
                        message: "注册失败！验证码错误/过期"
                    })
                } else if (err.code == 70007) {
                    prompt.showToast({
                        message: "注册失败！用户名已被注册"
                    })
                } else if (err.code == 70002) {
                    prompt.showToast({
                        message: "注册失败！密码不规范/不一致"
                    })
                } else {
                    prompt.showToast({
                        message: "注册失败！请检查用户名/密码/邮箱"
                    })
                }
            }
        }
        );
    },
    get_all_token() {
        let url  = this.$app.$def.data.usermgmtIP + '/v1/identity/verifycode-image'
        let httpRequest = http.createHttp();
        httpRequest.on('napi_headersReceive', (data) => {
            console.info('napi_header: ' + data.header);
        });
        httpRequest.request(
            url,
            {
                method: 'GET', // 可选，默认为“GET”
                header: {
                    'Content-Type': 'image/jpeg',
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                var lresult = new Uint8Array(data.result);
                var that = new util.Base64();
                var finresult = that.encodeToStringSync(lresult);
                this.pic = "data:image/jpeg;base64," + finresult;
                this.token = data.cookies.substring(data.cookies.length-130, data.cookies.length-94);
                this.session = data.cookies.substring(data.cookies.length-32);
                this.onVerify();
            } else {
                console.info('napi_error:' + err);
                httpRequest.destroy();
            }
        }
        );
    },
    onRegiste(){
        router.push({
            uri: 'pages/register/register'
        })
    },
    onBack() {
        router.push({
            uri: 'pages/login/login'
        })
    }
}
